package org.ht.viewer;

import java.awt.Container;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.io.File;
import java.lang.reflect.Field;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import javax.sql.DataSource;
import javax.swing.AbstractAction;
import javax.swing.AbstractButton;
import javax.swing.Action;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.JToggleButton.ToggleButtonModel;

import org.azj.ImageEditor.ImageEditor;
import org.azj.ImageEditor.ImagePreparer;
import org.azj.ImageEditor.RectifyPatientPrepare;
import org.azj.dbOperatorComponent.IDbNonQueryOperation;
import org.azj.dbOperatorComponent.OperableTable;
import org.azj.logHelper.LOG;
import org.azj.logHelper.LOG_COMPONENT;
import org.azj.logHelper.LOG_LEVEL;
import org.ht.controller.ControlCaseDialog;
import org.ht.database.DataBase;
import org.ht.entity.Case;
import org.ht.entity.ImageTag;
import org.ht.exception.CannotOmitException;
import org.ht.global.DbTableNames;
import org.ht.util.StringUtil;
import org.ht.viewer.calendar.JDatePicker;
import org.swixml.SwingEngine;

import com.jgoodies.forms.layout.CellConstraints;

/*
 * 新建病例对话框
 */
public class CaseDialog {

	public static final int TYPE_NEW = 1;
	public static final int TYPE_UPDATE = 2;
	public static final int TYPE_LOOK = 3;

	// swixml 引擎
	SwingEngine swix = new SwingEngine(this);
	JDialog dialog;
	CaseDialog thisclass;
	private Case thecase;
	private ControlCaseDialog controller = new ControlCaseDialog(this);

	// 关闭dialog后的结果
	private int colseResult = JOptionPane.DEFAULT_OPTION;

	// 是否是新建病例
	private boolean isnewcase = false;

	public int getColseResult() {
		return colseResult;
	}

	public CaseDialog(Case thecase, int type) {
		thisclass = this;

		if (thecase == null || type == TYPE_NEW) {
			thecase = new Case();
			isnewcase = true;
		}
		this.thecase = thecase;
		String configs = System.getProperty("user.dir")
				+ "\\xml\\CaseDialog.xml";
		try {
			dialog = (JDialog) swix.render(new File(configs));
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 初始化
		init();
		// 填充病例
		fillwithcase();
		// 如果是新病例就填充默认值
		if (isnewcase) {
			fillDefult();
		} else {
			// 不是新病例就填充图像信息
			fillImage();
			if (type == TYPE_LOOK) {
				button_ok.setVisible(false);
				button_cancel.setText("关闭");
			}
		}
	}

	public void setVisible(boolean b) {
		dialog.setVisible(b);
	}

	// 特殊控件
	JPanel enter_hospital_date_panel;
	JDatePicker InHospotialDate;
//	JPanel DisBreakOutDt_panel;
//	JDatePicker DisBreakOutDt;
//	JPanel VisitTime_panel;
//	JDatePicker VisitTime;
	JTextField DisBreakOutDt;
	JTextField VisitTime;
	

	// 选项禁用MultiPanel
	JPanel HasTreatBeforeInMulti;
	JPanel HasPainMulti;
	JPanel HasCombinedDieaseMulti;
	JPanel HasBacteriaGrowingMulti;
	JPanel HasOpAssistantDeviceMulti;
	JPanel IsNeedFlushMulti;
	JPanel UseDrainMulti;
	JPanel HasUseAntibioticPostOpMulti;
	JPanel HasPainPostOpMulti;
	JPanel HasPostOpPainHealMulti;
	JPanel HasAnalFistulaMulti;
	JPanel HasPostOpFeverMulti;
	// 基本表的对象

	JTextField Name;
	ButtonGroup Sex;
	public JTextField PatientId;
	JTextField AgeInHospital;
	JTextField Tel;
	JLabel label;
	GridBagLayout layout;
	CellConstraints cc;

	// 术前表的对象
	JRadioButton HasTreatBeforeIn;

	JCheckBox NotKnownAntibiotic;
	JCheckBox BetaLactam;
	JCheckBox Aminoglycoside;
	JCheckBox Macrolide;
	JCheckBox Quinolones;
	JCheckBox Nitroimidazole;
	JCheckBox OtherAntibiotic;
	JCheckBox SuppositoryTreatment;
	JCheckBox ElectuaryTreatment;
	JCheckBox WaterAquaTreatment;
	JCheckBox OtherTreatment;

	JTextField BodyTemprature;
	JRadioButton HasPain;

	JCheckBox SlightPain;
	JCheckBox IntermediatePain;
	JCheckBox IntensivePain;
	JCheckBox DefeTmLT1PD;
	JCheckBox DefeTmEQ1PD;
	JCheckBox DefeTmGT1PD;

	JCheckBox DefeTexSlurry;
	JCheckBox DefeTexHard;
	JCheckBox DefeTexSoftShape;

	JCheckBox PeeFluent;
	JCheckBox PeeNeedAdjust;
	JCheckBox PeeNotFluent;

	JRadioButton HasCombinedDiease;
	JCheckBox DiabetesMellitus;
	JCheckBox Hypertension;
	JCheckBox HeartDis;
	JCheckBox IntestinalDis;
	JCheckBox BloodDis;
	JCheckBox CerebrovascularDis;
	JCheckBox Cancer;
	JCheckBox OtherCombineDis;

	JTextArea HistoryDis;

	JRadioButton DisScale12;
	JRadioButton DisScale23;
	JRadioButton DisScale34;
	JRadioButton HasBreak;
	JRadioButton IsExplicitPain;
	JRadioButton HasExplicitFlucSense;
	JRadioButton HasSwelling;
	JRadioButton HasNormalSkinTempr;

	JTextField PreOpWBC;
	JTextField PreOpN;
	JTextField PreOpCRP;
	JTextField PreOpBloodSugar;
	JTextArea PreOpOtherException;

	// 影像部分
	public JTextField img_mri;
	public JTextField img_b;
	public JTextField img_ct;
	public JTextField img_x;
	JButton btn_img_mri;
	JButton btn_img_b;
	JButton btn_img_ct;
	JButton btn_img_x;
	public List<String> img_mrilist = new ArrayList<String>();
	public List<String> img_blist = new ArrayList<String>();
	public List<String> img_ctlist = new ArrayList<String>();
	public List<String> img_xlist = new ArrayList<String>();

	// 术中表
	JCheckBox LumbarAnesthesia;
	JCheckBox PartialAnesthesia;
	JCheckBox IntravenousAnesthesia;
	JCheckBox OtherAnesthesia;
	JCheckBox SimpleIncision;
	JCheckBox MultiIncision;
	JCheckBox FullScaleIncision;
	JCheckBox HealOpDraggingWires;
	JCheckBox HealOpCathetering;
	JCheckBox HealOpSeton;

	JRadioButton HasInnercut;
	JRadioButton HasPusCultivation;
	JRadioButton HasBacteriaGrowing;

	JCheckBox EscherichiaColi;
	JCheckBox KlebsiellaPneumoniae;
	JCheckBox PseudomonasAeruginosa;
	JCheckBox StaphylococcusAureus;
	JCheckBox ProteusMirabilis;
	JCheckBox EnterobacterCloacae;
	JCheckBox OtherBacteria;

	JRadioButton HasOpAssistantDevice;

	JCheckBox OpAssistantCUSA;
	JCheckBox OpAssistantElecKnife;
	JCheckBox OpAssistantOther;

	// 术后表
	JRadioButton IsNeedFlush;
	JCheckBox NaClFlush;
	JCheckBox PerhydrolFlush;
	JCheckBox MetronidazoleFlush;
	JCheckBox RecoverLiquidFlush;
	JCheckBox OtherFlush;

	JRadioButton UseDrain;
	JCheckBox RedOilQauze;
	JCheckBox VaselineQauze;
	JCheckBox FuracilinQauze;
	JCheckBox WriteJadeQauze;
	JCheckBox RecoverLiquidQauze;
	JCheckBox OtherDrain;

	JCheckBox CottonOppression;
	JCheckBox MedicineLineDrain;
	JCheckBox NegativePressureDrain;
	JCheckBox OtherHealMethod;

	JRadioButton HasPostOpFever;
	JTextField PostOpBodyTemp;

	JCheckBox PysicalDT;
	JCheckBox IndomethacinSuppositoryDT;
	JCheckBox AntifebrileInjectionDT;

	JRadioButton HasUseAntibioticPostOp;
	JCheckBox BetaLactamPostOp;
	JCheckBox AminoglycosidePostOp;
	JCheckBox MacrolidePostOp;
	JCheckBox QuinolonesPostOp;
	JCheckBox NitroimidazolePostOp;
	JCheckBox OtherAntibioticPostOp;
	JCheckBox OtherDropTemperatureMethod;

	JRadioButton HasPainPostOp;
	JCheckBox SlightPainPostOp;
	JCheckBox IntermediatePainPostOp;
	JCheckBox IntensivePainPostOp;

	JRadioButton HasPostOpPainHeal;
	JCheckBox OralPainKiller;
	JCheckBox MusleInjectionPainKiller;
	JCheckBox IndomethacinPainKiller;
	JCheckBox EarPointPainKiller;
	JCheckBox AcupuncturePainKiller;
	JCheckBox OtherPainHealMethod;

	JCheckBox NonDetain;
	JCheckBox OneDayDetain;
	JCheckBox TwoDayDetain;
	JCheckBox ThreeDayDetain;
	JCheckBox MoreDayDetain;

	JCheckBox PeeLess1hPullTube;
	JCheckBox Pee1to6hPullTube;
	JCheckBox Pee6to12hPullTube;
	JCheckBox Pee12to24hPullTube;
	JCheckBox PeeMore24hPullTube;

	JCheckBox DefeLess6hPullTube;
	JCheckBox Defe6to24hPullTube;
	JCheckBox Defe24to48hPullTube;
	JCheckBox Defe48to72hPullTube;
	JCheckBox DefeMore72hPullTube;

	JCheckBox WarmSitzBath;
	JCheckBox Enema;
	JCheckBox Paroline;
	JCheckBox MarenSoftCapsule;
	JCheckBox Congrongtongbian;
	JCheckBox RunchangTablets;
	JCheckBox FoliumSennae;
	JCheckBox Duphalac;
	JCheckBox SFPEG;
	JCheckBox Heshuang;
	JCheckBox OtherDefeHelpWay;

	JTextField DaysInHospital;
	JTextField WoundHealingTime;

	JCheckBox WellHeal;
	JCheckBox BadHeal;

	JCheckBox PostOpAnusFuncNormal;
	JCheckBox PostOpAnusFuncSlightIncontinence;
	JCheckBox PostOpAnusFuncIntensiveIncontinence;

	JRadioButton HasAnalFistula;
	JCheckBox SimplePureFistula;
	JCheckBox SimpleComplexFistula;
	JCheckBox DangerPureFistula;
	JCheckBox DangerComplexFistula;

	JCheckBox VisitAnusFuncNormal;
	JCheckBox VisitAnusFuncSlightIncontinence;
	JCheckBox VisitAnusFuncIntensiveIncontinence;
	JCheckBox AnorectalStenosis;

	JRadioButton HasReoccure;

	JButton button_ok;
	JButton button_cancel;

	/**
	 * 初始化
	 */
	private void init() {
		// 如果非新建病例,则不允许修改病历号
		if (!isnewcase) {
			PatientId.setEditable(false);
		}

		// 日期控件
		InHospotialDate = new JDatePicker(JDatePicker.STYLE_CN_DATE1);
		enter_hospital_date_panel.add(InHospotialDate);
//		DisBreakOutDt = new JDatePicker(JDatePicker.STYLE_CN_DATE1);
//		DisBreakOutDt_panel.add(DisBreakOutDt);
//		VisitTime = new JDatePicker(JDatePicker.STYLE_CN_DATE1);
//		VisitTime_panel.add(VisitTime);

		// 影像部分
		setImgLookButton(btn_img_mri);
		setImgLookButton(btn_img_b);
		setImgLookButton(btn_img_ct);
		setImgLookButton(btn_img_x);

		// 选项禁用
		try {
			reflectAddItemListener("HasTreatBeforeIn");
			reflectAddItemListener("HasPain");
			reflectAddItemListener("HasCombinedDiease");
			reflectAddItemListener("HasBacteriaGrowing");
			reflectAddItemListener("HasOpAssistantDevice");
			reflectAddItemListener("IsNeedFlush");
			reflectAddItemListener("UseDrain");
			reflectAddItemListener("HasUseAntibioticPostOp");
			reflectAddItemListener("HasPainPostOp");
			reflectAddItemListener("HasPostOpPainHeal");
			reflectAddItemListener("HasAnalFistula");
			reflectAddItemListener("HasPostOpFever");

		} catch (NoSuchFieldException | SecurityException
				| IllegalArgumentException | IllegalAccessException e1) {
			e1.printStackTrace();
		}

		// HasTreatBeforeIn.addItemListener(new ItemListener() {
		//
		// @Override
		// public void itemStateChanged(ItemEvent e) {
		// JRadioButton jop = (JRadioButton) e.getSource();
		// // TODO 两种做法隐藏或者disable
		// // if (!jop.isSelected()) {
		// // TreatInBeforeMulti.setVisible(false);
		// // } else {
		// // TreatInBeforeMulti.setVisible(true);
		// // }
		// if (!jop.isSelected()) {
		// disable(TreatInBeforeMulti);
		// } else {
		// enable(TreatInBeforeMulti);
		// }
		// }
		// });
	}

	/**
	 * 默认值填充
	 */
	private void fillDefult() {
		AgeInHospital.setText("0");
		BodyTemprature.setText("37");
		PostOpBodyTemp.setText("37");
	}

	/**
	 * 反射批量disable禁用选项
	 * 
	 * @param target
	 * @throws SecurityException
	 * @throws NoSuchFieldException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 */
	private void reflectAddItemListener(String name)
			throws NoSuchFieldException, SecurityException,
			IllegalArgumentException, IllegalAccessException {
		// 获取radio对象
		Field field = this.getClass().getDeclaredField(name);
		Object obj = field.get(this);
		// 获取容器
		Field field2 = this.getClass().getDeclaredField(name + "Multi");
		Object obj2 = field2.get(this);
		if (obj instanceof JRadioButton) {
			if (obj2 instanceof Container) {
				JRadioButton jRadioButton = (JRadioButton) obj;
				Container container = (Container) obj2;
				jRadioButton.addItemListener(new ItemListenerEntity(container));
				// 先置为选中
				jRadioButton.setSelected(true);
			}
		}
	}

	// private void modifyEditorForImage(JTextField jTextField){
	// jTextField.gete
	// }

	/**
	 * 设置清除图片按钮的属性
	 * 
	 * @param button
	 */
	private void setImgLookButton(JButton button) {
		button.setIcon(IconUtil.getIcon("look.jpg"));
		button.setBorderPainted(false);
		button.setBorder(null);
	}

	/**
	 * 填充病例
	 */
	private void fillwithcase() {
		// 填充非图片信息
		HashMap<String, String> property = thecase.getProperty();
		Iterator<Entry<String, String>> iter = property.entrySet().iterator();
		while (iter.hasNext()) {
			Entry<String, String> entry = (Entry<String, String>) iter.next();
			String key = entry.getKey();
			String val = entry.getValue();
			setText(key, val);
		}

	}

	// TODO 填充图片信息
	/**
	 * 填充图像信息
	 */
	private void fillImage() {
		// 填充非图片信息
		String pid = thecase.getPid();
		List<String> urls = controller.queryImagesByPid(pid);
		img_mri.setText(urls.get(0));
		img_b.setText(urls.get(1));
		img_ct.setText(urls.get(2));
		img_x.setText(urls.get(3));
	}

	/**
	 * 获取4个图像控件的信息
	 */
	public ArrayList<ImageTag> getImageURL() {
		ArrayList<ImageTag> result = new ArrayList<ImageTag>();
		String[] urls;
		String text;
		if (!(text = img_mri.getText()).isEmpty()) {
			urls = text.split(";");
			for (String url : urls) {
				result.add(new ImageTag(ImageTag.img_mri, url));
			}
		}
		if (!(text = img_b.getText()).isEmpty()) {
			urls = text.split(";");
			for (String url : urls) {
				result.add(new ImageTag(ImageTag.img_b, url));
			}
		}
		if (!(text = img_ct.getText()).isEmpty()) {
			urls = text.split(";");
			for (String url : urls) {
				result.add(new ImageTag(ImageTag.img_ct, url));
			}
		}
		if (!(text = img_x.getText()).isEmpty()) {
			urls = text.split(";");
			for (String url : urls) {
				result.add(new ImageTag(ImageTag.img_x, url));
			}
		}
		return result;

	}

	/**
	 * 根据key获取控件并填充
	 */
	public void setText(String key, String val) {
		if (key == null) {
			assert key != null;
			return;
		}
		try {
			Field field = this.getClass().getDeclaredField(key);
			Object obj = field.get(this);
			// 先处理特殊控件
			switch (key) {
			case "InHospotialDate":
				((JDatePicker) obj).setSelectedDateString(val);
				return;
//			case "DisBreakOutDt":
//				((JDatePicker) obj).setSelectedDateString(val);
//				return;
//			case "VisitTime":
//				((JDatePicker) obj).setSelectedDateString(val);
//				return;
			}

			if (obj instanceof JFormattedTextField) {
				((JFormattedTextField) obj).setText(val);
			}
			if (obj instanceof ButtonGroup) {
				ButtonGroup group = (ButtonGroup) obj;
				Enumeration<AbstractButton> enu = group.getElements();
				while (enu.hasMoreElements()) {
					AbstractButton radioButton = enu.nextElement();
					if (radioButton.getText().equals(val)) {
						radioButton.setSelected(true);
					}
				}
			}

			if (obj instanceof JToggleButton) {
				JToggleButton toggleButton = (JToggleButton) obj;
				if (toggleButton.getModel() instanceof ToggleButtonModel) {
					ButtonGroup group = ((ToggleButtonModel) toggleButton
							.getModel()).getGroup();
					if (group != null && group.getButtonCount() == 2) {
						// group.clearSelection();
						boolean b = Boolean.parseBoolean(val);
						if (b) {
							toggleButton.setSelected(true);
						} else {
							Enumeration<AbstractButton> e = group.getElements();
							while (e.hasMoreElements()) {
								AbstractButton ab = e.nextElement();
								if (ab != toggleButton) {
									ab.setSelected(true);
								}

							}
						}

					}else{
						toggleButton.setSelected(Boolean.parseBoolean(val));
					}
				} else {
					toggleButton.setSelected(Boolean.parseBoolean(val));
				}
			}
			// if (obj instanceof JCheckBox) {
			// JCheckBox checkBox = (JCheckBox) obj;
			// checkBox.setSelected(Boolean.parseBoolean(val));
			// }
			// if (obj instanceof JRadioButton) {
			// JRadioButton radioButton = (JRadioButton) obj;
			// radioButton.setSelected(Boolean.parseBoolean(val));
			// }
			if (obj instanceof JTextField) {
				JTextField textField = (JTextField) obj;
				textField.setText(val);
			}
			if (obj instanceof JTextArea) {
				JTextArea textField = (JTextArea) obj;
				textField.setText(val);
			}
		} catch (NoSuchFieldException e) {
			System.out.println("界面内" + e.getMessage() + "未定义");
		} catch (SecurityException | IllegalArgumentException
				| IllegalAccessException e) {
			e.printStackTrace();
		}
		return;
	}

	/**
	 * 根据key获取控件内容转成string
	 */
	public String getText(String key) {
		String val = null;
		if (key == null) {
			assert key != null;
			return val;
		}
		try {
			Field field = this.getClass().getDeclaredField(key);
			Object obj = field.get(this);
			// 先处理特殊控件
			switch (key) {
			case "InHospotialDate":
				val = ((JDatePicker) obj).getSelectedDateString();
				return val;
//			case "DisBreakOutDt":
//				val = ((JDatePicker) obj).getSelectedDateString();
//				return val;
//			case "VisitTime":
//				val = ((JDatePicker) obj).getSelectedDateString();
//				return val;
			}

			if (obj instanceof JFormattedTextField) {
				val = ((JFormattedTextField) obj).getText();
			}
			if (obj instanceof ButtonGroup) {
				ButtonGroup group = (ButtonGroup) obj;
				Enumeration<AbstractButton> enu = group.getElements();
				while (enu.hasMoreElements()) {
					AbstractButton radioButton = enu.nextElement();
					if (radioButton.isSelected()) {
						val = radioButton.getText();
					}
				}
			}
			if (obj instanceof JCheckBox) {
				JCheckBox checkBox = (JCheckBox) obj;
				val = String.valueOf(checkBox.isSelected());

			}
			if (obj instanceof JRadioButton) {
				JRadioButton radioButton = (JRadioButton) obj;
				val = String.valueOf(radioButton.isSelected());
			}
			if (obj instanceof JTextField) {
				JTextField textField = (JTextField) obj;
				val = textField.getText();
			}
			if (obj instanceof JTextArea) {
				JTextArea textField = (JTextArea) obj;
				val = textField.getText();
			}
		} catch (NoSuchFieldException e) {
			System.out.println("界面内" + e.getMessage() + "未定义");
		} catch (SecurityException | IllegalArgumentException
				| IllegalAccessException e) {
			e.printStackTrace();
		}
		return val;
	}

	/**
	 * 点击确定按钮
	 */
	public Action okAction = new AbstractAction() {
		private static final long serialVersionUID = 1L;

		public void actionPerformed(ActionEvent e) {
			LOG.WriteLog("正在保存病例," + "正在处理的ID为[" + PatientId.getText() + "]");

			boolean result = false;
			try {
				if (isnewcase) {
					result = controller.save(thecase);
				} else {
					result = controller.update(thecase);
				}
			} catch (CannotOmitException e1) {
				LOG.WriteLog(LOG_LEVEL.WARNING,
						LOG_COMPONENT.LOG_COMP_DB_CHANGE, e1.getMessage());
			} catch (Exception e1) {
				LOG.WriteLog(LOG_LEVEL.CRITICAL,
						LOG_COMPONENT.LOG_COMP_DB_CHANGE, "病例保存错误,"
								+ "正在处理的ID为[" + PatientId.getText() + "]");
				e1.printStackTrace();
			} finally {
				if (result) {
					colseResult = JOptionPane.OK_OPTION;
					dialog.dispose();
				}
			}

		}
	};

	public Action cancelAction = new AbstractAction() {
		private static final long serialVersionUID = 1L;

		public void actionPerformed(ActionEvent e) {
			colseResult = JOptionPane.CANCEL_OPTION;
			dialog.dispose();
		}
	};

	public Action imgAction = new AbstractAction() {
		private static final long serialVersionUID = 1L;

		public void actionPerformed(ActionEvent e) {
			JFileChooser chooser = new JFileChooser();
			// Note: source for ExampleFileFilter can be found in
			// FileChooserDemo,
			// under the demo/jfc directory in the JDK.
			ImageFileFilter filter = new ImageFileFilter();
			filter.addExtension("jpg");
			filter.addExtension("gif");
			filter.setDescription("JPG & GIF Images");
			chooser.setFileFilter(filter);
			chooser.setMultiSelectionEnabled(true);
			int returnVal = chooser.showOpenDialog(dialog);
			if (returnVal == JFileChooser.APPROVE_OPTION) {
				File[] files = chooser.getSelectedFiles();
				JButton jb = (JButton) (e.getSource());
				Field field;
				JTextField jTextField = null;
				try {
					field = thisclass.getClass().getDeclaredField(jb.getName());
					jTextField = (JTextField) field.get(thisclass);
				} catch (NoSuchFieldException | SecurityException
						| IllegalArgumentException | IllegalAccessException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				for (File file : files) {
					jTextField.setText(jTextField.getText()
							+ file.getAbsolutePath() + ";");
				}
			}

		}
	};

	public Action imgLookAction = new AbstractAction() {
		private static final long serialVersionUID = 1L;

		public void actionPerformed(ActionEvent e) {

			JButton jb = (JButton) (e.getSource());
			Field field;
			JTextField jTextField = null;
			List<String> list = null;
			try {
				field = thisclass.getClass().getDeclaredField(jb.getName());
				jTextField = (JTextField) field.get(thisclass);
				field = thisclass.getClass().getDeclaredField(
						jb.getName() + "list");
				list = (List<String>) field.get(thisclass);
			} catch (NoSuchFieldException | SecurityException
					| IllegalArgumentException | IllegalAccessException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			String oldUrls = jTextField.getText();
			List<String> oldUrlsList = StringUtil.StringToList(oldUrls, ";");
			// 查看图片
			List<String> missing = lookimage(oldUrls);
			// 删除表中新加
			list.addAll(missing);

			oldUrlsList.removeAll(missing);
			String newUrls = StringUtil.ListToString(oldUrlsList, ";");
			jTextField.setText(newUrls);
		}
	};

	// 以后这个方法就直接拿去用
	private static List<String> lookimage(String denotation) {

		// TODO 把denotation的路径改掉
		File directory = new File("");

		// 临时文件夹
		SimpleDateFormat sDateFormat = new SimpleDateFormat(
				"yyyy-MM-dd-HH-mm-ss");
		String tmpFolderPath = System.getProperty("user.dir") + "\\tmp\\"
				+ sDateFormat.format(new Date());
		File file = new File(tmpFolderPath);
		file.deleteOnExit();
		file.mkdirs();

		// 实际调用的函数
		List<String> missingImgs = new ArrayList<String>();
		try {
			missingImgs = showImagesAndGetMissingImgs(denotation,
					tmpFolderPath, DataBase.getDataBase());
		} catch (Exception e) {
			// TODO: 出现了错误，展示给用户看，
		}
		return missingImgs;
	}

	// private static void 确定() {
	// // TODO： 先增加新的文件
	//
	// // 再删除原来的数据
	// if (false == deleteImages(missingImgs, DataBase.getDataBase())) {
	// // TODO: 出现了错误，展示给用户看，
	// }
	// }

	// 参数是我们的image list，以分号分割(也以分号结束）。如果是全路径则是本地文件，如果不是则是数据库中的id
	// 这里只需要修改表的名称等信息和函数签名
	private static List<String> showImagesAndGetMissingImgs(
			String imageDenotation, String tmpFolderPath, DataSource db2ds) {
		// split the denotations with ";"
		String[] imageDenotations = imageDenotation.split(";");
		List<String> imgList = Arrays.asList(imageDenotations);

		ImageEditor ieAdd = new ImageEditor();
		ImagePreparer ipAdd = null;

		try {
			// TODO 修改表名
			ipAdd = new RectifyPatientPrepare(db2ds, DbTableNames.SchemaName,
					DbTableNames.TblImage, "IMG", "imageId = %s");

			ieAdd.setImageFolderPath(tmpFolderPath);
			ieAdd.setImagePreparer(ipAdd);

			if (!ieAdd.showPictures(imgList)) {
				throw new Exception("图片不能被加载!");
			}

			return ieAdd.getMissingPictures();
		} catch (Exception e) {
			// TODO 写日志
		} finally {
			ieAdd.dispose();
		}

		return new ArrayList<String>();
	}

	// 调整表名和日志
	private static boolean deleteImages(List<String> toDeleteImages,
			DataSource ds) {

		IDbNonQueryOperation tableUnit = null;
		try {
			// TODO 修改表名
			tableUnit = new OperableTable(ds, DbTableNames.SchemaName,
					DbTableNames.TblImage);
		} catch (SQLException e) {
			// TODO 写日志
			return false;
		}

		String whereFilter;
		int id = 0;

		for (String toDeleteImage : toDeleteImages) {
			try {
				id = Integer.parseInt(toDeleteImage);
			} catch (NumberFormatException nfe) {
				continue;
			}
			whereFilter = String.format("id = %d", id);

			try {
				tableUnit.getDeleteCommand(whereFilter).doCommand(ds);
			} catch (SQLException e) {
				// TODO 写日志
				return false;
			}
		}

		return true;
	}
}
